# -*- -*- -*- -*- -*- -*- -*-
# @Author  : mengzhe
# @Time    : 2025/5/26 11:19
# @File    : server.py
# @function:
# @input   :
# @output  :
# @Software: PyCharm 
# -*- -*- -*- -*- -*- -*- -*-
import socket
import threading
from datetime import datetime

from utils import str_bytes_2_bytes

HOST = 'localhost'
PORT = 12345


def handle_client(conn, addr):
    print(f"\nConnected by {addr}")

    def receive_messages():
        while True:
            try:
                data = conn.recv(4096)  # 增大缓冲区以适应雷达数据
                if not data:
                    print(f"[Server] {addr} disconnected")
                    break

                current_time = datetime.now().strftime("%H:%M:%S.%f")[:-3]
                print(f"[Server][{current_time}] Received: {data}")

                if data[0]==0x33 and data[1]==0xCC:
                    response_str = ' '.join([f"{byte:02X}" for byte in data])
                    print(f"收到客户端反馈: {response_str[:400]}")

                if data[0]==0x3C and data[1]==0x3C:
                    response_str = ' '.join([f"{byte:02X}" for byte in data])
                    print(f"收到雷达反馈{response_str[:400]}")
                    # continue


            #     msg = data.decode().strip()
            #     current_time = datetime.now().strftime("%H:%M:%S.%f")[:-3]
            #
            #     if "[TIME]" in msg:
            #         time_part = msg.split("[TIME]")[1].split("[CNT]")[0].strip()
            #         counter = msg.split("[CNT]")[1].strip()
            #         print(f"[Server][{current_time}] Time report (Count: {counter}): {time_part}")
            #     elif "[PLC_REPORT]" in msg:
            #         data_part = msg.split("[PLC_REPORT]")[1].split("[CNT]")[0].strip()
            #         counter = msg.split("[CNT]")[1].strip()
            #         print(f"[Server][{current_time}] PLC data (Count: {counter}): {data_part[:50]}...")
            #     elif "[WS_REPORT]" in msg:
            #         data_part = msg.split("[WS_REPORT]")[1].split("[CNT]")[0].strip()
            #         counter = msg.split("[CNT]")[1].strip()
            #         print(f"[Server][{current_time}] Weather data (Count: {counter}): {data_part[:50]}...")
            #     elif "[RADAR_REPORT]" in msg:
            #         data_part = msg.split("[RADAR_REPORT]")[1].split("[CNT]")[0].strip()
            #         counter = msg.split("[CNT]")[1].strip()
            #         print(f"[Server][{current_time}] Radar data (Count: {counter}): {data_part[:100]}...")
            #     elif "[RADAR_RESPONSE]" in msg:
            #         response = msg.split("[RADAR_RESPONSE]")[1].split("[CNT]")[0].strip()
            #         counter = msg.split("[CNT]")[1].strip()
            #         print(f"[Server][{current_time}] Radar response (Count: {counter}): {response}")
            #     elif "[CNT]" in msg:
            #         feedback = msg.split("[CNT]")[0].strip()
            #         counter = msg.split("[CNT]")[1].strip()
            #         print(f"[Server][{current_time}] Command feedback (Count: {counter}): {feedback}")
            #     else:
            #         print(f"[Server][{current_time}] Received: {msg}")
            except (ConnectionResetError, BrokenPipeError):
                print("[Connection lost]")
                break

    # 启动接收线程
    recv_thread = threading.Thread(target=receive_messages, daemon=True)
    recv_thread.start()

    # 主线程处理命令输入
    try:
        while True:
            cmd = input("Enter command (or 'exit' to close connection): ")
            if cmd.lower() == 'exit':
                break
            if cmd.lower() == 'help':
                print("Available commands:")
                print("- 'exit': Close the connection")
                print("- 'help': Display this help message")
                continue
            if cmd[0:5] =='55 AA':
                print("[Server] instruction Code")
                conn.sendall(str_bytes_2_bytes(cmd))
                continue

            conn.sendall(cmd.encode())
    finally:
        conn.close()
    print("Waiting for new connection...")


def run_server():
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.bind((HOST, PORT))
        s.listen()
        print(f"Server started on {HOST}:{PORT}")
        while True:
            conn, addr = s.accept()
            handle_client(conn, addr)


if __name__ == "__main__":
    run_server()